package com.lovo.pis.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;


public class JwtUtil {

    private static String signature = "zhuiyi";

    public static String getToken(Map<String, String> userMap){
        //设置过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND,30);
        //创建JWT
        JWTCreator.Builder builder = JWT.create();
        //负载传入用户信息
        userMap.forEach((k,v)->builder.withClaim(k,v));
        //编码
        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(signature));
        return token;
    }

    public static Object decodeJwt(String token,String key){
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(signature)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            String value = decodedJWT.getClaim(key).asString();
            return value;
        }catch (TokenExpiredException e){
            return Boolean.FALSE;
        }
    }
}
